/*
 * @Author: MiNine
 * @Date: 2020-09-19 09:28:44
 * @LastEditors: MiNine
 * @LastEditTime: 2020-09-24 11:23:20
 * @LastEditors: MiNine
 * @LastEditTime: 2020-09-23 14:59:37
 * @Description: 
 */
const {
    Admin
} = require('../models/adminModel');

const {
    Client
} = require('../models/clientModel');

let jwt = require("jsonwebtoken")
const {
    TOKEN_KEY
} = require("../utils/const"); //常量的引入
const {
    uploadFiles,
    moveFiles,
    removeFiles
} = require("../utils/upload"); //图片上传需要

//用户登录，使用jwt验证
async function login(req, res, next) {
    const {
        account,
        password
    } = req.body

    const data = await Admin.find({
        account
    })
    if (data.length > 0) {
        let gotUser = data[0]
        if (gotUser.password == password) {
            if (gotUser.permission != 0) {
                //在token中封入id和权限
                let token = jwt.sign({
                        _id: gotUser._id,
                        permission: gotUser.permission
                    },
                    //引入token常量
                    TOKEN_KEY, {
                        expiresIn: 60 * 100
                    },
                )
                res.send({
                    data,
                    permission: data.permission,
                    token,
                    msg: "登录成功",
                    status: 1,
                })
            } else {
                res.send({
                    msg: "用户已被删除",
                    type: "user has been removed",
                    status: 0,
                })
            }
        } else {
            res.send({
                msg: "登陆失败，密码不正确",
                type: "wrong password",
                status: 0,
            })
        }
    } else {
        res.send({
            msg: "登陆失败，用户不存在",
            type: "user does not exist",
            status: 0
        })
    }

    //注释代码留作精简备用，不要删除!!!!!!!!!!!!


    // const data = await Admin.find({ account, password })
    // if (data.length > 0) {
    //     let gotUser = data[0]
    //     // console.info(gotUser.permission)
    //     if (gotUser.permission != 0) {
    //         let token = jwt.sign(
    //             { account },
    //             //引入token常量
    //             TOKEN_KEY,
    //             { expiresIn: 60 * 100 },
    //         )
    //         res.send({
    //             data,
    //             permission: data.permission,
    //             token,
    //             msg: "登录成功",
    //             status: 1,
    //         })
    //     } else {
    //         res.send({
    //             msg: "用户已被删除",
    //             status: 0,
    //         })
    //     }

    // } else {
    //     res.send({
    //         msg: "登录失败",
    //         status: 0
    //     })
    // }
}


//创建用户信息，以permission区分级别
async function addUser(req, res, next) {
    const {
        account,
        nickName,
        password = "admin123",
        permission,
        avatarUrl
    } = req.body
    const userAlreadyExists = await Admin.find({
        account
    })
    if (userAlreadyExists.length > 0) {
        res.send({
            msg: "用户名已经存在，请尝试其他用户名",
            status: 0,

        })
    } else {
        if (avatarUrl) { //判断头像存在与否，存在将缓存区的图片放在图片路径中,且将缓存区的文件夹删除
            moveFiles({
                fromPath: "./public/temp",
                toPath: "./public/images",
                filename: avatarUrl
            });
            removeFiles("./public/temp");
        }
        await Admin.create({
            account,
            nickName,
            password,
            permission,
            avatarUrl
        })

        res.send({
            msg: "注册成功",
            status: 1,
            data: {
                account,
                password
            }
        })
    }
}

//软删除用户
async function delUser(req, res, next) {
    const {
        _id
    } = req.body
    // await Admin.deleteOne({ _id })
    await Admin.updateOne({
        _id
    }, {
        permission: 0
    })
    res.send({
        msg: "成功删除用户",
        status: 1
    })

}

//修改信息
async function modUser(req, res, next) {
    const URL = 'http://localhost:3000/images/';
    const {
        _id,
        account,
        nickName,
        permission,
        avatarUrl
    } = req.body
    if (avatarUrl) { //判断头像存在与否，存在将缓存区的图片放在图片路径中,且将缓存区的文件夹删除
        moveFiles({
            fromPath: "./public/temp",
            toPath: "./public/images",
            filename: avatarUrl
        });
        removeFiles("./public/temp");
    }
    await Admin.updateOne({
        _id
    }, {
        account,
        nickName,
        permission,
        avatarUrl: URL + avatarUrl
    })
    res.send({
        msg: "修改用户信息成功",
        status: 1,
        data
    })
}

//修改销售员信息
async function modOrderStatus(req, res, next) {
    const {
        _id,
        account,
        password,
        nickName,
        permission = 5
    } = req.body
    const data = await Admin.updateOne({
        _id
    }, {
        account,
        password,
        nickName,
        permission
    })
    res.send({
        msg: "修改用户信息成功",
        status: 1,
        data
    })
}


async function getUsers(req, res, next) {
    console.info(req.body)
    let searchType = req.body.searchType
    let {
        pageSize = 3, currentPage = 1
    } = req.body.userData
    let total = await Admin.countDocuments()
    let totalPages = Math.ceil(total / pageSize)
    if (searchType == "") {
        let users = await Admin.find().limit(pageSize - 0).skip((currentPage - 1) * pageSize)
        res.send({
            msg: "获取用户数据成功",
            status: 1,
            userData: {
                users,
                total,
                currentPage,
                pageSize,
                totalPages
            }
        })
    } else {
        let users = await Admin.find({
            permission: searchType
        }).limit(pageSize - 0).skip((currentPage - 1) * pageSize)
        res.send({
            msg: "获取用户数据成功",
            status: 1,
            userData: {
                users,
                total,
                currentPage,
                pageSize,
                totalPages
            }
        })
    }

}


async function getClients(req, res, next) {
    let {
        _id
    } = req.body
    //populate+当前数据属性名，即可关联到其他数据库 // 备用 : .populate("insureOrdList").populate("claimOrdList")
    let gotUser = await Admin.find({
        _id
    }).populate("clientList")
    console.info(gotUser)
    let gotClients = gotUser[0].clientList
    console.info(gotClients)
    res.send({
        msg: "获取该销售员名下所有客户成功",
        status: 1,
        gotClients
    })


}


async function uploadUserAvatar(req, res) {
    const images = uploadFiles({
        path: "./public/temp"
    }); //路径以app.js作为参考
    images(req, res, (err) => {
        if (err) {
            console.info("上传失败" + err)
        } else {
            res.send({
                status: 1,
                massage: "上传成功",
                data: req.files[0].filename //将图片的路径返回去
            })
        }
    })
}



module.exports = {
    addUser,
    login,
    delUser,
    modUser,
    getUsers,
    getClients,
    modOrderStatus,
    uploadUserAvatar
}